package yinhang;

public class Bank implements IDao{
	
	private User[] users;
	private int index; 
	
	public Bank() {
		users = new User[10];
	}

	@Override
	public boolean regist(User user) {
		if(index >= users.length) {
			return false;
		}
		users[index++] = user;
		return true;
	}

	private int getIndexByCardId(int id) {
		for(int i = 0 ;i < index; i++) {
			if(users[i].getCardId() == id) {
				return i;
			}
		}
		return -1;
	}
	
	@Override
	public boolean delete(User user) {
		int i = getIndexByCardId(user.getCardId());
		if(-1 == i) {
			return false;
		}
		for(int j = i+1; j < index; j++) {
			users[j-1] = users[j];
		}
		users[--index] = null;
		return true;
	}

	@Override
	public boolean saveMoney(User user, double money) {
		int i = getIndexByCardId(user.getCardId());
		if(-1 == i) {
			return false;
		}
		if(money > 0) {
			users[i].setMoney(users[i].getMoney()+money);
			return true;
		}else {
			return false;
		}
	}

	@Override
	public boolean withDraw(User user, double money) {
		int i = getIndexByCardId(user.getCardId());
		if(-1 == i) {
			return false;
		}
		if(users[i].getMoney() < money && money > 0) {
			return false;
		}else {
			users[i].setMoney(users[i].getMoney()-money);
			return true;
		}
	}

	@Override
	public boolean transportMoney(User user1, User user2, double money) {
		int i1 = getIndexByCardId(user1.getCardId());
		int i2 = getIndexByCardId(user2.getCardId());
		if(-1 == i1 || -1 == i2) {
			return false;
		}
		if(withDraw(user1, money)) {
			saveMoney(user2, money);
		}
		return true;
	}

	@Override
	public User selectByName(String name) {
		for(int i = 0 ;i < index; i++) {
			if(users[i].getName().equals(name)) {
				return users[i];
			}
		}
		return null;
	}
}
